package com.mud.mudcommune.view.fragment.twoLevel;


import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.mud.mudcommune.R;
import com.mud.mudcommune.adapter.ChiefAdapter;
import com.mud.mudcommune.entry.ChiefEntry;
import com.mud.mudcommune.entry.ChiefResponse;
import com.mud.mudcommune.entry.SucceedResponse;
import com.mud.mudcommune.view.fragment.threeLevel.ChiefDetailsFragment;
import com.mud.mudcommune.utils.LogUtils;
import com.mud.mudcommune.http.ApiService;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ChiefFragment extends Fragment implements View.OnClickListener, AdapterView.OnItemClickListener, Callback<ChiefResponse> {
    private static final String TAG = ChiefFragment.class.getSimpleName();
    private static ChiefFragment fragment = new ChiefFragment();
    @BindView(R.id.chief_list)
    PullToRefreshListView mPullToRefreshListView;
    @BindView(R.id.rb_designer)
    RadioButton designer;
    @BindView(R.id.rb_foreman)
    RadioButton foreman;
    @BindView(R.id.chief_back)
    ImageView backImg;
    private ChiefAdapter chiefAdapter;
    private Unbinder unbinder;
    private List<ChiefEntry> chiefList;
    private ListView mListView;
    private View view;
    private int pager=1;
    private List<ChiefEntry> notifyList=null;
    Call<ChiefResponse> caseTypeResponse=null;
    public ChiefFragment() {
    }

    public static Fragment getInstance() {
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_cheif, container, false);
        this.view=view;
        unbinder = ButterKnife.bind(this, view);
        requestDate(1); // 加载前十条数据
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        designer.setOnClickListener(this);
        foreman.setOnClickListener(this);
        backImg.setOnClickListener(this);
    }

    // 请求数据
    private void requestDate(int pager) {
        this.pager=pager;
        Retrofit retrofit = new Retrofit.Builder().baseUrl(ApiService.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        ApiService apiService = retrofit.create(ApiService.class);
        caseTypeResponse = apiService.getChief(pager);
        caseTypeResponse.enqueue(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rb_designer:
                designer.setBackgroundResource(R.drawable.capsule_btn_left_select);
                designer.setTextColor(getResources().getColor(R.color.white));
                foreman.setBackgroundResource(R.drawable.capsule_btn_right);
                foreman.setTextColor(getResources().getColor(R.color.black));
                break;
            case R.id.rb_foreman:
                designer.setBackgroundResource(R.drawable.capsule_btn_left);
                designer.setTextColor(getResources().getColor(R.color.black));
                foreman.setBackgroundResource(R.drawable.capsule_btn_right_select);
                foreman.setTextColor(getResources().getColor(R.color.white));
                break;
            case R.id.chief_back:
                getFragmentManager().popBackStack();
                break;
        }
    }

    @Override
    public void onResponse(Call<ChiefResponse> call, Response<ChiefResponse> response) {
        List<ChiefEntry> chiefList=null;
        ChiefResponse mChiefResponse = response.body();
        if(mChiefResponse!=null){
             chiefList = mChiefResponse.getChiefList();//NullPointerException
        }
        if(mChiefResponse.getStatus()==200&&pager==1){
            this.chiefList = chiefList;
            chiefAdapter = new ChiefAdapter(this.chiefList);
            mPullToRefreshListView.setOnItemClickListener(this);
            mPullToRefreshListView.setAdapter(chiefAdapter);
            notifyList=chiefList;//第一次进行赋值
        }else {
            if(chiefList!=null&&chiefList.size()!=0){
                for (int i = 0; i < chiefList.size(); i++) {
                    ChiefEntry chiefEntry = chiefList.get(i);
                    notifyList.add(chiefEntry);
                }
            }
            chiefAdapter.notifyDataSetChanged();//数据更新
            if(mPullToRefreshListView!=null){
                mPullToRefreshListView.onRefreshComplete();//停止更新
            }
        }
        initpulltorefresh(chiefAdapter);

    }

    @Override
    public void onFailure(Call<ChiefResponse> call, Throwable t) {
        t.printStackTrace();
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

        getFragmentManager().beginTransaction()
                .addToBackStack(null)
                .hide(ChiefFragment.getInstance())
                .add(R.id.main_frame, ChiefDetailsFragment.getInstance())
                .commit();

        Retrofit retrofit = new Retrofit.Builder().baseUrl(ApiService.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        ApiService apiService = retrofit.create(ApiService.class);
        Call<SucceedResponse> response = apiService.addBorrow(1);
        response.enqueue(new Callback<SucceedResponse>() {
            @Override
            public void onResponse(Call<SucceedResponse> call, Response<SucceedResponse> response) {
                LogUtils.i(TAG, "浏览量加一");
            }

            @Override
            public void onFailure(Call<SucceedResponse> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }

    private void initpulltorefresh(ChiefAdapter adapter) {
        //初始化控件
        if(mPullToRefreshListView==null){//老是报空指针异常
            ButterKnife.bind(this, view);//和视图进行绑定
        }
        mListView = mPullToRefreshListView.getRefreshableView();//NullPointerException
        mListView.setAdapter(adapter);
        //设置pull-to-refresh模式为Mode.Both
        mPullToRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_END);//只有上拉加载更多
        //设置上拉下拉事件
        mPullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {

            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                if(refreshView.isFooterShown()){
                    Toast.makeText(getContext(), "数据正在加载中...", Toast.LENGTH_SHORT).show();
                    new GetListDataTask().execute();
                }
            }
        });
    }

    private class GetListDataTask extends AsyncTask<Object, Object, List<ChiefEntry>> {
        @Override
        protected List<ChiefEntry> doInBackground(Object... params) {
            try {
                Thread.sleep(2000);
                requestDate(++pager);
            } catch (InterruptedException e) {
            }
            return null;
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }
}
